<template>
  <div class="page-wrapper w-100 h-100 ">
    <div class="w-100 h-100 map-container" id="map-container"></div>


    <Head :tianqi="tianqi">

      <div class="header-box text-max d-flex justify-content-center align-items-center pb-4">

        <div class="d-flex align-items-center justify-content-center mr-5">
          <div class="button-item mr-3">养殖日志</div>
          <div class="button-item mr-3">智能控制</div>
          <div class="button-item mr-3" @click="$router.push('/home')">监控大屏</div>
          <div class="mx-5">{{ base_name || '上海海洋大学智慧养殖平台' }}</div>
          <div class="button-item">数据中心</div>
        </div>
      </div>
    </Head>
    <aside class="common-box position-absolute top-0 left-box">
      <div class="h-70 pb-2">
        <Item title="设施列表">
          <ul class="area-list">
            <li v-for="i in shelist" :key="i.ID" class="flex-item mb-3">
              <div class="flex-content" @click="xuanshebei(i, i.ID)">{{ i.BACILITIES_NAME }}</div>
              <div class="tag" :class="{ 'tag-success': i.STATE === 2 }">运行正常</div>
            </li>
          </ul>
        </Item>
      </div>
      <div class="h-30 pb-2" >
        <Item title="控制面板">
          <div class="w-100 h-100 overflow-hidden"  >
            <el-col >
              <div class="row">
                <img src="../assets/img/立体光标2.png" alt=""
                style="width: 110px; margin-left:50px;margin-top: -3%;position:relative;">  
                <div class="link-text" style="margin-top:50px;margin-left:-110px" @click="doSetting(active)" options="list.get(active)">
                  塘口数量：78
                </div>
                <img src="../assets/img/立体光标.png" alt=""
                style="width: 110px; margin-left:70px;margin-top: 0%;position:relative;">   
                <span class="link-text2" style="margin-top:50px;margin-left:70px" options="list.get(active)">
                  读取参数
                </span> 
              </div>
              <div class="row"> 
                <img src="../assets/img/立体光标.png" alt=""
                style="width: 110px; margin-left:50px;margin-top: 2%;position:relative;">
                <span class="link-text2" style="margin-top:36%;margin-left:-110px" options="list.get(active)">
                  投饲机数量:6
                </span>
                <img src="../assets/img/立体光标2.png" alt=""
                style="width: 110px; margin-left:70px;margin-top: 0%;position:relative;"> 
                <span class="link-text" style="margin-top:36%;margin-left:70px" options="list.get(active)" @click="showAddDialog()">
                  投饲设置
                </span>   

              </div>
            </el-col>
          </div>
        </Item>
      </div>
    </aside>
    <section class="bottom-box d-flex align-items-center">
      <aside class="common-box w-50 h-100 pt-4 border-box mr-2">
        <Item >
          <zhexian1 style="height:300%;transform: scale(0.95);" :dailyfeedlist="dailyfeedlist"></zhexian1>
        </Item>
      </aside>
      <aside class="common-box w-50 h-100 pt-4 border-box">
        <Item >
          <zhexian2 style="height:300%;transform: scale(0.95);" :planlist="planlist"></zhexian2>
        </Item>
      </aside>
    </section>
    <aside class="common-box position-absolute top-0 right-box">
      <div class="h-70 pb-2 border-box">
        <Item :title="tianjiarizhi">
          <el-form :model="addForm">
            <el-form-item prop="time">
              <el-date-picker v-model="addForm.time" value-format="yyyy-MM-dd%20HH:mm" placeholder="请选择时间"
                @change="check_form" />
            </el-form-item>
            <el-form-item prop="name">
              <el-input v-model="addForm.name" placeholder="请填写操作人姓名" @change="check_form" />
            </el-form-item>
            <el-form-item prop="action">
              <el-select v-model="addForm.action" placeholder="请选择动作" @change="check_form">
                <el-option v-for="(item, index) in actionOptions" :key="index" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item prop="action">
              <el-input v-model="addForm.zhonglei" type="index" placeholder="请填写种类" @change="check_form" />
            </el-form-item>
            <el-form-item prop="num">
              <el-input v-model="addForm.num" type="index" placeholder="请填写数量" @change="check_form" />
            </el-form-item>
            <el-form-item prop="remark">
              <el-input type="textarea" :rows="2" v-model="addForm.remark" placeholder="请填写备注" @change="check_form">
              </el-input>
            </el-form-item>

            <el-form-item class="text-right">
              {{ errMsg }}
              <el-button :loading="addLoading" class="linear-bg__primary" @click="addLog" ref="submit"
                :disabled="isdisabled">提交
              </el-button>

            </el-form-item>
          </el-form>
        </Item>
      </div>
      <div class="h-30">
        <Item title="日志记录">
          <div class="w-100 h-100 overflow-hidden">
            <ul class="log-list">
              <li v-for="(item, index) in loglist" :key="index"
                class="d-flex align-items-center justify-content-between mb-2">
                <div class="text-main">{{ item.content }}</div>
                <div class="text-title">{{ item.time }}</div>
              </li>
            </ul>
          </div>
        </Item>
      </div>
    </aside>
    <el-dialog :visible.sync="addDialogVisible"  :modal="false"  title="新增设置信息" width="30%" :append-to-body="false">
      <el-form :model="newSettingsForm" label-width="80px">
          <!-- 塘口号 -->
          <el-form-item label="塘口号" prop="pond_number">
              <el-input v-model="newSettingsForm.pond_number"></el-input>
          </el-form-item>
  
          <!-- 投饲机号 -->
          <el-form-item label="投饲机号" prop="feeder_number">
              <el-input v-model="newSettingsForm.feeder_number"></el-input>
          </el-form-item>
  
          <!-- 鱼数量 -->
          <el-form-item label="鱼数量/条" prop="fish_quantity">
              <el-input v-model="newSettingsForm.fish_quantity"></el-input>
          </el-form-item>
  
          <!-- 鱼规格 -->
          <el-form-item label="鱼规格/g" prop="fish_specification">
              <el-input v-model="newSettingsForm.fish_specification"></el-input>
          </el-form-item>
  
          <!-- 饲料系数 -->
          <el-form-item label="饲料系数" prop="feed_coefficient">
              <el-input v-model="newSettingsForm.feed_coefficient"></el-input>
          </el-form-item>
  
          <!-- 日饵率 -->
          <el-form-item label="日饵率" prop="daily_feed_rate">
              <el-input v-model="newSettingsForm.daily_feed_rate"></el-input>
          </el-form-item>

  
          <!-- 其他表单项 -->
      </el-form>
  
      <div slot="footer" class="dialog-footer">
          <el-button @click="closeAddDialog()">取消</el-button>
          <el-button type="primary" @click="addNewSettings()">确定</el-button>
      </div>
    </el-dialog>
    <div v-if="box === 1" class="equip-box">
      <img src="@/assets/img/frame.png" alt="">
      <div class="text" style="white-space: pre-wrap;">{{miaoshu}}</div>
      <div class="close-icon d-flex align-items-center justify-content-center" @click="onCloseCover">
        <svg t="1639825855503" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
          p-id="26567" width="1rem" height="1rem">
          <path
            d="M846.005097 957.24155c-28.587082 0-57.174164-10.911514-78.996169-32.733519L96.632851 254.131955c-43.644009-43.644009-43.644009-114.348328 0-157.992337s114.348328-43.644009 157.992337 0L925.001265 766.515694c43.644009 43.644009 43.644009 114.348328 0 157.992337C903.17926 946.330036 874.592179 957.24155 846.005097 957.24155z"
            p-id="26568" fill="#ffffff"></path>
          <path
            d="M175.62902 957.24155c-28.587082 0-57.174164-10.911514-78.996169-32.733519-43.644009-43.644009-43.644009-114.348328 0-157.992337L767.008928 96.139617c43.644009-43.644009 114.348328-43.644009 157.992337 0s43.644009 114.348328 0 157.992337L254.625188 924.508032C232.803183 946.330036 204.216101 957.24155 175.62902 957.24155z"
            p-id="26569" fill="#ffffff"></path>
        </svg>
      </div>
    </div>
  </div>
</template>

<script>
import { cultiverlistv2, add_cultiver, caicon, shebeilistv2, GetDailyData,AddSettings } from '@/request/api';
import zhexian1 from "../components/dailyfeedzhexian.vue";
import zhexian2 from "../components/fishweightzhexian.vue";
export default {
  components: {
      zhexian1,
      zhexian2,
    },
  name: 'Cultiver',
  data() {
    return {
      planlist:[],
      dailyfeedlist:[],
      allData:[],
      addDialogVisible: false, 
      newSettingsForm:{
        pond_number:'',
        feeder_number:'',
        fish_quantity:'',
        fish_specification:'',
        feed_coefficient:'',
        daily_feed_rate:'',
        set_date:'',
      },
      box: 0,
      isdisabled: true,//按钮不可点击
      tianqi: {},
      temp: {},
      rizhishuru: 0,
      tianjiarizhi: '添加日志',
      map: '',
      shelist: [],
      zuobiaolist: [],
      base_name: "",
      miaoshu: "",
      param:'1',
      equipList: [],
      actionOptions: [
        { name: '投饲料', value: '投饲料' },
        { name: '投药物', value: '投药物' },
        { name: '捕捞水产品', value: '捕捞水产品' },
        { name: '投放水产品', value: '投放水产品' },
        // 捕捞水产品和投放水产品
      ],
      typeOptions: [ // 随actionOption选择而变化
        { name: '饲料1', value: 1 },
        { name: '饲料2', value: 2 }
      ],
      addForm: {
        time: '',
        name: '',
        action: '',
        // type: '',
        num: '',
        remark: '',
        zhonglei: '',
        sheshiid: '',
        base_id:'',
      },
      addFromName: {
        sheshiid: '点击左侧设施选择，设施号',
        time: '时间',
        name: '操作人姓名',
        action: '动作',
        // type: '种类',
        zhonglei: '种类',
        num: '数量',
        // remark: '备注',
        
        
        
      },

      addLoading: false,
      loglist: [

      ],
      errMsg: '',
      dis: true,
    }
  },
  mounted() {
    
    this.getEquipList();
    this.getList();
    this.renderMap();
    this.GetFeedplan();
  },
  methods: {
    // 渲染地图
    GetFeedplan(){
      this.param = '1';
      GetDailyData() // 假设 GetDailyData 是用于从后端获取数据的函数
        .then(response => {
            // 检查 response.FishFeedingPlan 是否已定义
            if (response.FishFeedingPlan) {
                // 确保 this.allData 是一个数组
                this.allData = Array.isArray(response.FishFeedingPlan) ? response.FishFeedingPlan : [];
                // 确保 this.active 已定义并有效
                console.log('this.param:', this.param);
                if (this.param !== undefined) {
                  // console.log('this.allData:', this.allData);
                    // 筛选符合条件的数据
                    const filteredData = this.allData.filter(item => item.pond_number === this.param);

                    // 输出筛选后的数据以确认
                    console.log('筛选后的数据:', filteredData);
                    
                    // 提取 plan_date, daily_feed_amount 和 fish_quantity 并保存到 planlist 和 dailyfeedlist
                    this.planlist = filteredData.map(item => ({
                        plan_date: item.plan_date,
                        fish_specification: item.fish_specification,
                    }));
                    this.dailyfeedlist = filteredData.map(item => ({
                        plan_date: item.plan_date,
                        daily_feed_amount: item.daily_feed_amount,
                    }));

                    // 输出结果以确认
                    //console.log('planlist:', this.planlist);
                    //console.log('dailyfeedlist:', this.dailyfeedlist);
                } else {
                    console.error('active 未定义');
                }
            } else {
                console.error('FishFeedingPlan 数据未定义');
            }
        })
        .catch(error => {
            console.error('获取数据时发生错误:', error);
        });
    },
    showAddDialog() { 
          this.addDialogVisible = true;
    },
    closeAddDialog() { 
          this.addDialogVisible = false;
    }, 
    addNewSettings() {
        // 将设置信息保存到数据中
        const newSettings = {
            // 填入设置信息字段
            pond_number: this.newSettingsForm.pond_number,
            feeder_number: this.newSettingsForm.feeder_number,
            fish_quantity: this.newSettingsForm.fish_quantity,
            fish_specification: this.newSettingsForm.fish_specification,
            feed_coefficient: this.newSettingsForm.feed_coefficient,
            daily_feed_rate: this.newSettingsForm.daily_feed_rate,
            // 其他设置信息字段
        };

        // 添加完成后关闭对话框
        console.log('New Settings Data:', newSettings);
        this.closeAddDialog();

        // 调用后端接口添加设置信息
        this.addSettingsToBackend(newSettings);
    },
    addSettingsToBackend(newSettings) {
        AddSettings(newSettings) // 假设 AddSettings 是你用于将设置信息添加到后端的函数
            .then(response => {
                console.log('Settings added successfully'); 
                // 在成功添加设置信息后，可以调用方法刷新数据
            })
            .catch(error => {
                // 如果发生错误，可以在这里进行错误处理
                console.error('An error occurred:', error);
            });
    },
    xuanshebei(i, id) {
      this.box = 0;
      this.rizhishuru = 1;
      this.addForm.sheshiid = id;
      this.tianjiarizhi = "添加日志 " + i.BACILITIES_NAME;
      //  点击设备设置中心位置
      
      this.map.setCenter([i.BACILITIES_LOCATION.split(',')[0], i.BACILITIES_LOCATION.split(',')[1]]);
        
      
    },
    renderMap() {
      this.$AMapLoader.load({
        key: 'bb41d02b6376f70646e2490b6bf5f80b',
        version: '1.4.15',
        plugins: ['AMap.MapType'], // 添加地图类型切换插件
        AMapUI: {
          version: '1.1',
          plugins: []
        },
        Loca: {
          version: '1.3.2'
        }
      }).then((AMap) => {
        this.map = new AMap.Map('map-container', {
          // 移除了 mapStyle，让普通地图显示默认颜色（绿色大陆、蓝色海域）
          // mapStyle: 'amap://styles/blue', // 注释掉以显示默认地图颜色
          layers: [new AMap.TileLayer.Satellite(),new AMap.TileLayer.RoadNet()],

          zoom: 18,
          // center: this.zuobiaolist[0]
          center: this.shelist[0].BACILITIES_LOCATION.split(',')
        });
        
        // 添加地图类型切换控件
        this.map.addControl(new AMap.MapType({
          defaultType: 1 // 0代表默认地图，1代表卫星地图
        }));
        
        // const list = this.zuobiaolist;

        async function ca_icon(local) {
          let icon = '';
          // await caicon({ zuobiao: local }).then(res => {
          //   if (res && res.data == "水质检测") {
          //     icon = new AMap.Icon({
          //       size: new AMap.Size(40, 50), // 图标尺寸
          //       // image: require('@/assets/img/location.svg'), // Icon的图像
          //       image: require('@/assets/img/shuizhi.svg'), // Icon的图像
          //       imageSize: new AMap.Size(40, 50) // 根据所设置的大小拉伸或压缩图片
          //     });
          //   } else {
          //     icon = new AMap.Icon({
          //       size: new AMap.Size(40, 50), // 图标尺寸
          //       image: require('@/assets/img/location2.svg'), // Icon的图像
          //       // image: require('@/assets/img/shexiangtou.svg'), // Icon的图像
          //       imageSize: new AMap.Size(40, 50) // 根据所设置的大小拉伸或压缩图片
          //     });
          //   }
          // })
          icon = new AMap.Icon({
                size: new AMap.Size(40, 50), // 图标尺寸
                image: require('@/assets/img/breeding.svg'), // Icon的图像
                // image: require('@/assets/img/shexiangtou.svg'), // Icon的图像
                imageSize: new AMap.Size(40, 50) // 根据所设置的大小拉伸或压缩图片
              });
          return icon;
        }

        this.shelist.forEach(async (item) => {
          let icon = await ca_icon(item)//等待await后面的函数完后才能之后再返回icon
          const marker = new AMap.Marker({
            position: item.BACILITIES_LOCATION.split(','),
            offset: new AMap.Pixel(-20, -25), // 偏移值
            icon,
            label: {
              content: item.BACILITIES_NAME,
              //offset: new AMap.Pixel(27, 25)
             
            },
          })
          marker.on('click', () => {
            this.box = 1;
            this.map.setCenter(item.BACILITIES_LOCATION.split(','));
            const zuobiaopinStr = item.BACILITIES_LOCATION
                this.miaoshu = "设施名:" + item.BACILITIES_NAME + "\n设施类型:" + item.BACILITIES_TYPE+ "\n设施描述:" + item.INTRODUCE 
          })
          this.map.add(marker);
        })
      })
    },
    onCloseCover() {
      this.box = 0;
    },

    // 获取设施列表
    getEquipList() {
      this.base_name = this.$route.query.base_name;
      cultiverlistv2({
        base_id: this.$route.query.base_id
      }).then(res => {
        console.log("resres")
        console.log(res)
        // this.shelist = res.data.shebeilist;
        this.zuobiaolist = res.data.zuobiaoilist;
        this.loglist = res.data.loglist;
        this.tianqi = res.data.tianqi;
        // this.alertlist = res.data.alertlist;
        this.renderMap();
      })
    },
    getList() {
      this.base_name = this.$route.query.base_name;
      shebeilistv2({
        base_id: this.$route.query.base_id
      }).then(res => {

        this.shelist = res.data.sheshilist;
        this.renderMap();
      })
    },
    // 添加日志
    addLog() {
      this.addLoading = false;
      this.addForm.base_id=this.$route.query.base_id
      console.log(this.addForm);
      add_cultiver(
        this.addForm 
      ).then(res => {
        console.log("日志")
        console.log(res)
        this.addLoading = false;
        this.loglist = res.data.loglist;
        this.alertlist = res.data.alertlist;
        alert('提交成功')
      }).catch(function (error) {
        alert('提交失败' + error)
      })

      this.rizhishuru = 0;
      // 发送请求添加日志
    },
    //检查表单内容完整性
    check_form(e) {
      // this.errMsg = []
      this.errMsg = ''
      for (var key in this.addFromName) {
        // console.log(this.addForm)
        // console.log(this.addForm[key])
        // console.log(key)
        if (!this.addForm[key]) {
          this.isdisabled = true;
          // this.errMsg.push(key + '不能为空')
          // console.log(key)
          this.errMsg = this.addFromName[key] + '不能为空'
          return ''
        }
      }
      this.isdisabled = false;
      // this.$refs.submit.classList.remove('is-disabled')
      // console.log('ok')
      this.errMsg = ''

    }
  },
}
</script>

<style lang="less" scoped>
/deep/.amap-marker-label {
  border: 0;
  background-color: transparent;
  padding-left: 20px;
}

.page-wrapper {
  background-image: url("~@/assets/img/bg.png");
  background-size: 100% 100%;

  .map-container {
    opacity: 0.7;
  }

  .header-box {
    padding-right: 20rem;


  }

  .left-box {
    left: 1rem;

    .area-list {
      li {
        line-height: 1.6rem;
      }
    }
  }
  .bottom-box {
    position: absolute;
    top: 62%;
    left: 50%;
    transform: translate(-50%, 0);
    width: calc(50% - 5rem);
  }
  
  /deep/ .right-box {
    right: 1rem;

    .el-input__inner,
    .el-textarea__inner {
      background: rgba(4, 41, 87, 0.8) !important;
      border: 0.2rem solid transparent;
      border-radius: 0.5rem !important;
      font-size: 1rem;
      color: #fff;
      box-sizing: border-box;

      &:focus {
        border: 0.2rem solid #4cb2ff;
      }

      &.el-input__inner {
        height: 3rem;
      }
    }

    .el-button {
      font-size: 1.25rem;
      padding: 0.8rem 2rem;
      color: #fff;
      border: none;
    }
  }

  .log-list {
    line-height: 2rem;
  }

  //  地图设备提示框样式
  .equip-box {
    position: absolute;
    top: 30%;
    left: 50%;

    img {
      width: 25rem;
    }

    .text {
      position: absolute;
      top: 0;
      left: 0;
      color: #fff;
      padding: 2.5rem 3.5rem;
    }
    .close-icon {
      position: absolute;
      top: -2.5rem;
      right: 0rem;
      width: 2.4rem;
      height: 2.4rem;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 0.3rem;
    }
  }
  .link-text {
    color: hsl(49, 89%, 65%); /* 设置字体颜色为蓝色 */
    cursor: pointer; /* 设置鼠标悬停时为手型 */
    position: absolute; /* 使文本绝对定位 */
    top: 0; /* 设置文本距离容器顶部的距离 */
    left: 50%; /* 设置文本水平居中 */
    transform: translateX(-50%); /* 使文本水平居中对齐 */
    font-size: 15px; 
    /*font-weight: bold; /* 字体加粗 */
    font-family: 'Arial Rounded MT Bold', Arial, sans-serif; /* 使用圆润字体 */
    line-height: 2; /* 调整行高 */
    text-shadow: 2px 2px 2px rgba(165, 227, 72, 0.5); /* 添加文本阴影 */
    transition: color 0.3s, text-shadow 0.3s; /* 添加过渡效果 */
    letter-spacing: 1.5px; /* 设置字间距 */
  
  }
  .link-text::before {
    content: ''; /* 必须设置内容 */
    position: absolute;
    top: -10px; /* 调整为需要的距离 */
    left: -10px; /* 调整为需要的距离 */
    right: -10px; /* 调整为需要的距离 */
    bottom: -20px; /* 调整为需要的距离 */
    background: transparent; /* 背景透明 */
    z-index: -1; /* 保证伪元素在文本后面 */
  }
  .link-text:hover {
    color: #3ab8b7; /* 悬停时改变字体颜色 */
    text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.8); /* 悬停时改变文本阴影 */
  }
  .link-text2 {
    color: hsl(180, 97%, 53%); /* 设置字体颜色为蓝色 */
    cursor: pointer; /* 设置鼠标悬停时为手型 */
    position: absolute; /* 使文本绝对定位 */
    top: 0; /* 设置文本距离容器顶部的距离 */
    left: 50%; /* 设置文本水平居中 */
    transform: translateX(-50%); /* 使文本水平居中对齐 */
    font-size: 15px; 
    /*font-weight: bold; /* 字体加粗 */
    font-family: 'Arial Rounded MT Bold', Arial, sans-serif; /* 使用圆润字体 */
    line-height: 2; /* 调整行高 */
    text-shadow: 2px 2px 2px rgba(165, 227, 72, 0.5); /* 添加文本阴影 */
    transition: color 0.3s, text-shadow 0.3s; /* 添加过渡效果 */
    letter-spacing: 1.5px; /* 设置字间距 */
  }
  .link-text2::before {
    content: ''; /* 必须设置内容 */
    position: absolute;
    top: -10px; /* 调整为需要的距离 */
    left: -10px; /* 调整为需要的距离 */
    right: -10px; /* 调整为需要的距离 */
    bottom: -20px; /* 调整为需要的距离 */
    background: transparent; /* 背景透明 */
    z-index: -1; /* 保证伪元素在文本后面 */
  }
  .link-text2:hover {
    color: #3ab8b7; /* 悬停时改变字体颜色 */
    text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.8); /* 悬停时改变文本阴影 */
  }
}
</style>